package com.reliable.service.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class CustomRobotUtil {

    public static OapiRobotSendResponse sendTextMessage(String url, String secret, String message) {
        try {
            String sign = "";
            String[] parts = url.split("access_token=");
            String token = parts.length > 1 ? parts[1] : "";
            Long timestamp = System.currentTimeMillis();
            if (!StringUtils.isEmpty(secret)) {
                String stringToSign = timestamp + "\n" + secret;
                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
                byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
                sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            }
            //sign字段和timestamp字段必须拼接到请求URL上，否则会出现 310000 的错误信息
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);
            OapiRobotSendRequest req = new OapiRobotSendRequest();
            /**
             * 发送文本消息
             */
            //定义文本内容
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(message);
            //定义 @ 对象
//            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//            at.setAtUserIds(Arrays.asList(USER_ID));
            //设置消息类型
            req.setMsgtype("text");
            req.setText(text);
            //req.setAt(at);
            OapiRobotSendResponse rsp = client.execute(req, token);

            return rsp;
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

    }

    public static OapiRobotSendResponse sendMarkdownMessage(String url,String secret, String message,String title) {
        try {
            String sign = "";
                // 机器人webhook对应的access_token的值，不是client_id和client_secret生成的应用access_token
            String[] parts = url.split("access_token=");
            String accessToken = parts.length > 1 ? parts[1] : "";
            Long timestamp = System.currentTimeMillis();
            if (!StringUtils.isEmpty(secret)) {
                String stringToSign = timestamp + "\n" + secret;
                Mac mac = Mac.getInstance("HmacSHA256");
                mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
                byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
                sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            }
               // String accessToken = "机器人webhook对应的access_token的值";
                // 创建钉钉客户端
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?sign=" + sign + "&timestamp=" + timestamp);
                // 构建请求对象
                OapiRobotSendRequest req = new OapiRobotSendRequest();
                req.setMsgtype("markdown"); // 消息类型为markdown
                OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
                markdown.setTitle(title); // 标题
                markdown.setText(message); // markdown内容
                req.setMarkdown(markdown);
                // 构建@信息
                OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//                at.setIsAtAll(false); // 是否@所有人
//                // 指定@的用户ID列表
//                at.setAtUserIds(Arrays.asList("024759202052757723", "4525232859750548"));
//                req.setAt(at);
                // 发送请求
                OapiRobotSendResponse rsp = client.execute(req, accessToken);
                System.out.println(rsp.getBody()); // 输出返回结果
            return rsp;

        } catch (ApiException e) {
                e.printStackTrace();
            return null;
            } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    }

}
